<template>
  <div v-if="currentCode === 522">
    <div class="flex justify-end"
         style="margin-bottom:16px;">
      <div class="alert inline-flex items-center">
        <span style="margin-right:6px;font-size:12px">⚠️</span>
        {{capitalize(widgetName)}}&nbsp;
        has expired, please
        &nbsp;
        <span @click="onPurchase('app')"
              type="text"
              style="cursor: pointer;color:#17B3A3;line-height:1;padding:0">make a payment</span>
      </div>
    </div>
    {{$slots.default}}
  </div>
  <el-card v-else-if="currentCode === 518"
           v-bind="$attrs"
           :class="{ 'dashboard-intercept-consumer': true, 'dashboard-intercept-consumer--empty': empty }">
    <div class="dashboard-intercept-consumer__wrapper flex flex-col items-center">
      <el-image :src="require('@/assets/img/lock.png')"
                fit='fill'></el-image>
      <div class="dashboard-intercept-consumer__wrapper-title">You don't have permission yet!</div>
      <div v-if="$route.path!=='/nextTicket'" class="dashboard-intercept-consumer__wrapper-desc">Please ask admin to <span style="color: blue;text-decoration: underline;user-select: none;cursor: pointer;" @click="handleAssignALicense">assign a license</span> to your account so you can use {{comAppType}} feature.</div>
      <div v-else class="dashboard-intercept-consumer__wrapper-desc">Please ask admin to assign a license to your account so you can use {{comAppType}} feature.</div>
    </div>
  </el-card>
  <el-card v-else-if="currentCode === 519"
           v-bind="$attrs"
           :class="{ 'dashboard-intercept-consumer': true, 'dashboard-intercept-consumer--empty': empty }">
    <div class="dashboard-intercept-consumer__wrapper flex flex-col items-center">
      <el-image :src="require('@/assets/img/lock.png')"
                fit='fill'></el-image>
      <div class="dashboard-intercept-consumer__wrapper-title">Unavailable for viewing!</div>
      <div class="dashboard-intercept-consumer__wrapper-desc">{{capitalize(widgetName)}} has expired,please contact your administrator to make a payment.</div>
    </div>
  </el-card>
  <el-card v-else-if="currentCode === 419 || currentCode === 420 || currentCode === 421 ||currentCode === 424 || currentCode === 423 || currentCode === 422"
           v-bind="$attrs"
           :class="{ 'dashboard-intercept-consumer': true, 'dashboard-intercept-consumer--empty': empty }">
    <div class="w-full h-full flex flex-col relative">
      <div class="dashboard-intercept-consumer-header flex items-center"
           v-on="$listeners">
        <ZTooltip :content="widgetName"
                  :line="1">
          <span>{{widgetName}}</span>
        </ZTooltip>
      </div>
      <div class="dashboard-intercept-consumer-content relative  flex flex-col items-center">
        <div class="dashboard-intercept-consumer-content-mask absolute inset-0"
             :style="{backgroundImage: `url(${bg})` }"></div>
        <div class="dashboard-intercept-consumer-content-w absolute inset-0 flex justify-center flex-col items-center">
          <span style="width:240px;text-align:center;color:#606266;margin-bottom:12px" v-html="text"></span>
          <template v-if="currentCode !== 424 && currentCode !== 423">
            <el-button type="primary"
                       size="mini"
                       :style="{ width: '132px', 'marginBottom': '8px', display: !isBundleExpired ? 'inline-block' : 'none' }"
                       @click="onPurchase('bi')">Purchase</el-button>
            <el-button size="mini"
                       :style="{width: '132px', marginLeft: 0, display: demo ? 'inline-block' : 'none'}"
                       @click="onChat">Request Demo</el-button>
            <el-button type="text"
                       :loading="renewalLoading"
                       :style="{display: currentCode === 420 ? 'inline-block' : 'none' }"
                       @click="onRenewal(get(widget, 'data.code'), true)">14 days trial</el-button>
          </template>
        </div>
      </div>
    </div>
  </el-card>
  <div v-else>
    <slot></slot>
    <!-- {{loading === true ? null : $slots.default}} -->
  </div>
</template>

<script>
import ZTooltip from '@/components/storybook/z-tooltip'
import { InterceptContext } from './intercept-context'
import { get, isFunction, capitalize, hasIn, isEmpty } from 'lodash'
import Trail from '@/components/storybook/mixins/trail'
import Chat from '@/components/storybook/mixins/chat'
import { getWidgetMask } from '@/components/storybook/settings/widget'
export default {
  name: 'DashboardInterceptConsumer',
  mixins: [Trail, Chat],
  components: {
    ZTooltip
  },
  props: {
    gadgetId: String,
    beforeIntercept: Function,
    beforeLoading: [Boolean, String],
    empty: Boolean
  },
  data () {
    return {
      code: null,
      renewalLoading: false,
      capitalize,
      get
    }
  },
  computed: {
    comAppType () {
      return this.capitalize(this.widgetName) === 'Attendance' ? 'Attendance' : 'Next ticket'
    },
    widget () {
      return InterceptContext.widgets[this.gadgetId]
    },
    currentCode () {
      return this.code || get(this.widget, 'res.code')
    },
    widgetName () {
      const data = get(this.widget, 'data') || {}
      // eslint-disable-next-line
      return (data.widgetName || data.name || '').replace(/(\"|'*)/g, '')
    },
    bg () {
      return getWidgetMask(get(this.widget, 'data.gadgettype'))
    },

    /**
     * 420 还有14天
     * 421 过期了
     */
    isFree () {
      return InterceptContext.paidProducts === null || isEmpty(InterceptContext.paidProducts)
    },
    isBundleExpired () {
      const paidProducts = InterceptContext.paidProducts || {}
      const code = get(this.widget, 'data.code')
      return paidProducts.bundles === false && (!hasIn(paidProducts, code) || paidProducts[code] === false)
    },
    isBiExpired () {
      const paidProducts = InterceptContext.paidProducts || {}
      const code = get(this.widget, 'data.code')
      return hasIn(paidProducts, code) && paidProducts[code] === false && !this.isBundleExpired
    },
    text () {
      if (this.currentCode === 421 || this.currentCode === 420) {
        return 'Your free subscription to BI Package has expired. Please purchase the BI Package subscription to enable the widget. '
      }
      if (this.currentCode === 422) {
        return 'Your free subscription to BI Package has expired. Please purchase the BI Package subscription to enable the widget.'
      }
      if (this.currentCode === 424) {
        return 'Please select from the available BI package resources on the <a href="https://app.maibozhineng.com/Billing" style="color:#0081eb;text-decoration: underline;">Billing</a> page. '
      }
      if (this.currentCode === 423) {
        return 'The bundles you have purchased have expired. Please contact your administrator to renew your subscription. '
      }
      return this.isBundleExpired ? 'The Bundles you purchased has expired, please contact the administrator for renewal' : 'This is part of a BI package or bundle you purchased that has expired, please contact your administrator to renew it.'
    },
    demo () {
      return (this.currentCode === 421 || this.currentCode === 420) && this.isFree
    }
  },
  async created () {
    if (this.beforeIntercept && isFunction(this.beforeIntercept)) {
      this.$emit('update:beforeLoading', true)
      this.code = await this.beforeIntercept()
      this.$emit('update:beforeLoading', false)
    }
  },
  methods: {
    async onPurchase (active) {
      this.$root.eventBus.$emit('close', { dashboard: this.$route.path.includes('dashboard') })
      this.$router.push({
        path: '/marketplace',
        query: {
          active
        }
      })
    },
    handleAssignALicense () {
      this.$root.eventBus.$emit('event:handleAssignALicense')
    }
  }
}
</script>
<style lang="scss" scoped>
.el-alert {
  ::v-deep .el-alert__description {
    margin-top: 0;
  }
}
.alert {
  background-color: #fdf6ec;
  color: #e6a23c;
  padding: 6px 50px 6px 6px;
}
.dashboard-intercept-consumer {
  min-height: 280px;
  ::v-deep .el-card__body {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    background-color: #ffffff;
    left: 0;
  }
  &-header {
    padding: 0 16px;
    height: 30px;
    display: flex;
    align-items: center;
    font-weight: 700;
    font-size: 16px;
    color: #000;
    border-bottom: 1px solid #ebeef5;
  }
  &-content {
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 1;
    &-mask {
      background-size: 100% 100%;
      background-attachment: fixed;
      background-size: cover;
      z-index: 0;
      background-repeat: no-repeat;
      background-size: 100% 100%;
      filter: blur(17px);
    }
    &-w {
      z-index: 1;
      min-height: 280px;
    }
  }
  &__wrapper {
    max-width: 330px;
    text-align: center;
    .el-image {
      width: 180px;
    }
    &-title {
      font-size: 24px;
      color: #404040;
      padding: 16px 0;
      font-weight: 500;
    }
    &-desc {
      color: #bec0c5;
    }
  }
}
</style>
